/*
 * @Author: wuqingchun
 * @Date: 2024-09-24 17:28:45
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-09-24 19:52:21
 */

#include <libconfig.h++>

#include "chat_errno.h"
#include "chat_config.h"

CChatConfig& CChatConfig::GetInstance()
{
    static CChatConfig objInstance;

    return objInstance;
}

CChatConfig::CChatConfig()
{

}

int32_t CChatConfig::Init()
{
    int32_t iErr = CHAT_ERR_LOAD_CONFIG;

    libconfig::Config objConfig;

     /*
      解析配置文件。
    */
    try
    {
        // 读取配置文件
        objConfig.readFile("chat_server.cfg");
    }
    catch (const libconfig::FileIOException &fioex)
    {
        printf("I/O error while reading file, %s\n", fioex.what());
        return CHAT_ERR_LOAD_CONFIG;
    }
    catch (const libconfig::ParseException &pex)
    {
        printf("Parse error at %s:%d-%s\n", pex.getFile(), pex.getLine(), pex.getError());
        return CHAT_ERR_LOAD_CONFIG;
    }

    try
    {
        m_stMysqlConfig.strHost = objConfig.lookup("MysqlConfig.Host").c_str();
        m_stMysqlConfig.usPort = (int)objConfig.lookup("MysqlConfig.Port");
        m_stMysqlConfig.strUser = objConfig.lookup("MysqlConfig.User").c_str();
        m_stMysqlConfig.strPassword = objConfig.lookup("MysqlConfig.Password").c_str();
        m_stMysqlConfig.strDBName = objConfig.lookup("MysqlConfig.DatabaseName").c_str();
        m_stMysqlConfig.strCharset = objConfig.lookup("MysqlConfig.Charset").c_str();

        m_stRedisConfig.strHost = objConfig.lookup("RedisConfig.Host").c_str();
        m_stRedisConfig.usPort = (int)objConfig.lookup("RedisConfig.Port");

        m_stCommConfig.usListenPort = (int)objConfig.lookup("CommonConfig.ListenPort");
    }
    catch (const libconfig::SettingNotFoundException &refException)
    {
        printf("%s: %s\n", refException.what(), refException.getPath());
        return CHAT_ERR_LOAD_CONFIG;
    }
    catch (const libconfig::SettingException &refException)
    {
        printf("%s: %s\n", refException.what(), refException.getPath());
        return CHAT_ERR_LOAD_CONFIG;
    }

    return CHAT_ERR_OK;
}

const CHAT_MYSQL_CONFIG_S& CChatConfig::GetMysqlConfig() const
{
    return (const CHAT_MYSQL_CONFIG_S&)m_stMysqlConfig;
}

const CHAT_REDIS_CONFIG_S& CChatConfig::GetRedisConfig() const
{
    return (const CHAT_REDIS_CONFIG_S&)m_stRedisConfig;
}

const CHAT_COMMON_CONFIG_S& CChatConfig::GetCommonConfig() const
{
    return (const CHAT_COMMON_CONFIG_S&) m_stCommConfig;
}